package com.cityfood.controller;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cityfood.common.pojo.CartDisplay;
import com.cityfood.common.pojo.CityFoodResult;
import com.cityfood.common.utils.JsonUtils;
import com.cityfood.pojo.CfCart;
import com.cityfood.pojo.CfProduct;
import com.cityfood.pojo.CfProductSpecs;
import com.cityfood.service.CartService;
import com.cityfood.service.ProductService;
import com.cityfood.service.ProductSpecsService;

/**
 * @author 
 *操作管理员类以/userCart开头
 */
@Controller
public class CartController {
	
	@Autowired
	private CartService cartService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private ProductSpecsService productSpecsService;
	
	
	/**
	 * 查询根据用户id查询该用户的购物车商品，返回包装类CityFoodResult
	 */
	@RequestMapping(value="/cart",method=RequestMethod.GET)
	@ResponseBody
	public CityFoodResult getCartByUserId(HttpSession session,@RequestParam Integer userId) {
		CityFoodResult cityfoodResult = new CityFoodResult();
		//HttpSession session = req.getSession(false);
		Map<String,Integer> cartList = (Map<String,Integer>)session.getAttribute("cart");
		
		if (cartList==null) {
			CfCart cart = cartService.getCartByUserId(userId);
			if (cart==null) {
				cityfoodResult.setCode(201);
				cityfoodResult.setMsg("购物车空空如也");
				cityfoodResult.setData("{}");
				return cityfoodResult;
			}
			Map<String,Integer> jsonToList = (Map<String,Integer>)JsonUtils.jsonToMap(cart.getCartList());
			//根据cartList字符串解析出购物车
			List<CartDisplay> cartDisplays = this.getCartList(jsonToList);
			//放入session里面
			session.setAttribute("cart", jsonToList);
			
			cityfoodResult.setCode(200);
			cityfoodResult.setMsg("查询购物车成功");
			cityfoodResult.setData(cartDisplays);
			return cityfoodResult;
			
		}else{
			
			//根据cartList字符串解析出购物车
			List<CartDisplay> cartDisplays = this.getCartList(cartList);
			
			if (cartDisplays.size()>0) {
				cityfoodResult.setCode(200);
				cityfoodResult.setMsg("查询购物车成功");
				cityfoodResult.setData(cartDisplays);
				return cityfoodResult;
			}
		}
		cityfoodResult.setCode(201);
		cityfoodResult.setMsg("购物车空空如也");
		cityfoodResult.setData("{}");
		return cityfoodResult;
		
	}

	
	/**
	 * 添加购物车
	 */
	@RequestMapping(value = "/cart", method = RequestMethod.POST)
	@ResponseBody
	public CityFoodResult saveCart(HttpSession session, 
									@RequestParam Integer userId,
									@RequestParam String specsId, 
									@RequestParam Integer number) {

		CityFoodResult cityfoodResult = new CityFoodResult();
		//设置session时间一年
		session.setMaxInactiveInterval(60 * 60 * 24 * 365);
		
		// 根据用户id获取购物车信息
		CfCart cart = cartService.getCartByUserId(userId);
		if (cart == null) {
			//第一次添加购物车，之际存入一个
			Map<String, Integer> userCart = new LinkedHashMap<>();
			//存入
			userCart.put(specsId, number);
			CfCart newCart = new CfCart();
			//转为String
			String newCartList = JsonUtils.objectToJson(userCart);
			newCart.setUserId(userId);
			newCart.setCartList(newCartList);
			//更新
			int i = cartService.saveCart(newCart);
			if (i > 0) {
				// 放入session
				session.setAttribute("cart", userCart);
				cityfoodResult.setCode(200);
				cityfoodResult.setMsg("添加购物车成功");
				cityfoodResult.setData(true);
				return cityfoodResult;
			}
		}
		Map<String, Integer> userCart = (Map<String, Integer>)JsonUtils.jsonToMap(cart.getCartList());
		if (userCart.containsKey(specsId)) {
			userCart.put(specsId, userCart.get(specsId) + number);
		} else {
			userCart.put(specsId, number);
		}

		String newUserCart = JsonUtils.objectToJson(userCart);
		cart.setCartList(newUserCart);
		int i = cartService.updateCart(cart);
		if (i > 0) {
			// 放入session
			session.setAttribute("cart", userCart);
			cityfoodResult.setCode(200);
			cityfoodResult.setMsg("添加购物车成功");
			cityfoodResult.setData(true);
			return cityfoodResult;
		}

		cityfoodResult.setCode(201);
		cityfoodResult.setMsg("添加购物车失败");
		cityfoodResult.setData(false);
		return cityfoodResult;

	}
	
	/**
	 * 修改购物车商品规格
	 */
	@RequestMapping(value = "/cart/specs", method = RequestMethod.PUT)
	@ResponseBody
	public CityFoodResult updateCartSpecs(HttpSession session, @RequestParam Integer userId,
			@RequestParam String specsId, @RequestParam String afterSpecsId) {

		CityFoodResult cityfoodResult = new CityFoodResult();

		CfCart cart = cartService.getCartByUserId(userId);
		if (cart == null) {
			cityfoodResult.setCode(201);
			cityfoodResult.setMsg("修改购物车商品规格失败");
			cityfoodResult.setData(false);
			return cityfoodResult;
		}
		Map<String, Integer> cartList = (Map<String, Integer>)JsonUtils.jsonToMap(cart.getCartList());

		if (cartList.containsKey(specsId)) {
			Integer num = cartList.get(specsId);
			// 添加修改后的specsId
			cartList.put(afterSpecsId, num);
			// 删除原来的specsId
			cartList.remove(specsId);
		}

		String newCartList = JsonUtils.objectToJson(cartList);
		cart.setCartList(newCartList);
		int i = cartService.updateCart(cart);
		if (i > 0) {
			// 放入session
			session.setAttribute("cart", cartList);
			cityfoodResult.setCode(200);
			cityfoodResult.setMsg("修改购物车商品规格成功");
			cityfoodResult.setData(true);
			return cityfoodResult;
		}

		cityfoodResult.setCode(201);
		cityfoodResult.setMsg("修改购物车商品规格失败");
		cityfoodResult.setData(false);
		return cityfoodResult;
	}
	
	/**
	 * 结算购物车
	 */
	@RequestMapping(value="/cart/number",method=RequestMethod.PUT)
	@ResponseBody
	public CityFoodResult updateCartNumber(HttpSession session,
											@RequestParam Integer userId,
											@RequestParam String specsId,
											@RequestParam Integer number){
		
		CityFoodResult cityfoodResult = new CityFoodResult();
		
		CfCart cart = cartService.getCartByUserId(userId);
		
		if (cart==null) {
			cityfoodResult.setCode(201);
			cityfoodResult.setMsg("修改购物车商品数量失败");
			cityfoodResult.setData(false);
			return cityfoodResult;
		}
		
		Map<String, Integer> cartList = (Map<String, Integer>)JsonUtils.jsonToMap(cart.getCartList());

		for (String cartSpesc : cartList.keySet()) {
			if (cartSpesc.equals(specsId)) {
				// 修改商品数量
				cartList.put(cartSpesc, number);
			}
		}
		String newCartList = JsonUtils.objectToJson(cartList);
		cart.setCartList(newCartList);
		int i = cartService.updateCart(cart);
		if (i > 0) {
			// 放入session
			session.setAttribute("cart", cartList);
			cityfoodResult.setCode(200);
			cityfoodResult.setMsg("修改购物车商品数量成功");
			cityfoodResult.setData(true);
			return cityfoodResult;
		}
		
		cityfoodResult.setCode(201);
		cityfoodResult.setMsg("修改购物车商品数量失败");
		cityfoodResult.setData(false);
		return cityfoodResult;
	}
	
	/**
	 * 结算购物车
	 */
	@RequestMapping(value="/cart/buy",method=RequestMethod.POST)
	@ResponseBody
	public CityFoodResult Jiesuan(HttpSession session,@RequestParam String cartList){
		
		Map<String,Integer> list = (Map<String, Integer>)JsonUtils.jsonToMap(cartList);
		
		CityFoodResult cityfoodResult = new CityFoodResult();
		session.removeAttribute("buyCart");
		Map<String,Integer> buyCartList = new LinkedHashMap<>();
		
		for (String cartSpecs : list.keySet()) {
			
			CfProductSpecs specs = productSpecsService.getProductSpecsBySpecsId(Integer.parseInt(cartSpecs));
			
			if (specs.getStock()<list.get(cartSpecs)) {
				cityfoodResult.setCode(201);
				CfProduct product = productService.getProductByProductId(specs.getProductId());
				cityfoodResult.setMsg(product.getName()+"库存不足了,请减少购买数量");
				cityfoodResult.setData(false);
				return cityfoodResult;
			}else{
				buyCartList.put(cartSpecs, list.get(cartSpecs));
			}
		}
		session.setAttribute("buyCart", buyCartList);
		cityfoodResult.setCode(200);
		cityfoodResult.setMsg("结算购物车成功");
		cityfoodResult.setData(true);
		return cityfoodResult;
	}
	
	/**
	 * 删除购物车
	 */
	@RequestMapping(value="/cart",method=RequestMethod.DELETE)
	@ResponseBody
	public CityFoodResult deleteCart(HttpSession session,
									 @RequestParam Integer userId,
									 @RequestParam String specsIds){
		
		CityFoodResult cityfoodResult = new CityFoodResult();
		
		CfCart cart = cartService.getCartByUserId(userId);
		if (cart == null) {
			cityfoodResult.setCode(201);
			cityfoodResult.setMsg("删除购物车失败");
			cityfoodResult.setData(false);
			return cityfoodResult;
		}
		Map<String,Integer> userCart = (Map<String, Integer>)JsonUtils.jsonToMap(cart.getCartList());
		String[] ids = specsIds.split(",");
		for (String specsId : ids) {
			
			if (userCart.containsKey(specsId)) {
				userCart.remove(specsId);
			}
		}
		
		cart.setCartList(JsonUtils.objectToJson(userCart));
		int i = cartService.updateCart(cart);
		if (i > 0) {
			// 放入session
			session.setAttribute("cart", userCart);
			cityfoodResult.setCode(200);
			cityfoodResult.setMsg("删除购物车成功");
			cityfoodResult.setData(true);
			return cityfoodResult;
		}
		
		
		cityfoodResult.setCode(201);
		cityfoodResult.setMsg("删除购物车失败");
		cityfoodResult.setData(false);
		return cityfoodResult;
	}
	
	/**
	 * 购物车商品数量
	 */
	@RequestMapping(value = "/cartSize", method = RequestMethod.GET)
	@ResponseBody
	public CityFoodResult getCartSize(HttpSession session, @RequestParam Integer userId) {

		CityFoodResult cityfoodResult = new CityFoodResult();

		CfCart cart = cartService.getCartByUserId(userId);
		if (cart == null) {
			cityfoodResult.setCode(201);
			cityfoodResult.setMsg("查询购物车商品数量失败");
			cityfoodResult.setData(0);
			return cityfoodResult;
		}
		
		Map<String, Integer> newCartList = (Map<String, Integer>)JsonUtils.jsonToMap(cart.getCartList());

		cityfoodResult.setCode(200);
		cityfoodResult.setMsg("查询购物车商品数量成功");
		int size = 0;
		if (newCartList != null) {
			size = newCartList.size();
		}
		cityfoodResult.setData(size);
		return cityfoodResult;
	}
	
	public List<CartDisplay> getCartList(Map<String,Integer> cartList){
		List<CartDisplay> cartDisplays = new ArrayList<CartDisplay>();
		for (String cartSpecs : cartList.keySet()) {
			CfProductSpecs specs = productSpecsService.getProductSpecsBySpecsId(Integer.parseInt(cartSpecs));
			CfProduct product = productService.getProductByProductId(specs.getProductId());
			CartDisplay display = new CartDisplay();
			display.setSpecsId(specs.getId());
			display.setProductId(product.getId());
			display.setFoodName(product.getName());
			display.setPic(product.getMainImage());
			Map<String,String> specAttrs = (Map<String, String>)JsonUtils.jsonToMap(specs.getProductSpecs());
			String taste = "";
			for (String str : specAttrs.values()) {
				taste=str+"/"+taste;
			}
			taste=taste.substring(0, taste.length()-1);
			display.setTaste(taste);
			display.setNumber(cartList.get(cartSpecs));
			//Integer转换BigDecimal
			BigDecimal price  = new BigDecimal("0.00");
			if (specs.getPrice()!=null) {
				price = new BigDecimal(specs.getPrice().toString());
				price.setScale(2, RoundingMode.FLOOR);
			}
			display.setPrice(price.doubleValue());
			cartDisplays.add(display);
		}
		return cartDisplays;
	}
		
}
